<template>
  <div>
    <title-panel />
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-field
        readonly
        :value="obj.changeCircleDate"
        name="changeCircleDate"
        label="操作日期"
        placeholder="请选择时间"
        input-align="right"
        required
        @click="showPicker1 = true"
        :rules="[{ required: true, message: '请选择转日期' }]"
      />
      <van-popup v-if="!isDisabled" v-model="showPicker1" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @confirm="onConfirmStartDate"
          @cancel="showPicker1 = false"
        />
      </van-popup>

      <van-field
        readonly
        name="changeToHouseId"
        label="转入羊舍"
        :value="obj.changeToHouseId"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择转入羊舍' }]"
        @click="natureShows = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows" position="bottom">
        <van-picker
          show-toolbar
          :columns="houseS"
          value-key="landParcelName"
          @confirm="onConfirmType"
          @cancel="natureShows = false"
        />
      </van-popup>
      <!-- <van-field
        readonly
        name="changeToCricleId"
        label="转入羊圈"
        :value="obj.changeToCricleId"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择转入羊圈' }]"
        @click="natureShows2 = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows2" position="bottom">
        <van-picker
          show-toolbar
          :columns="circleS"
          value-key="landParcelName"
          @confirm="onConfirmType2"
          @cancel="natureShows2 = false"
        />
      </van-popup> -->
      <van-field
        readonly
        name="changeCricleReasonCode"
        label="转舍原因"
        :value="obj.changeCricleReasonCode"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择转舍原因' }]"
        @click="natureShows3 = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows3" position="bottom">
        <van-picker
          show-toolbar
          :columns="reasonS"
          value-key="landParcelName"
          @confirm="onConfirmType3"
          @cancel="natureShows3 = false"
        />
      </van-popup>
      <van-cell class="btnfrom" :border="false">
        <van-field
          :border="false"
          class="fromInput"
          readonly
          name="changeCricleCount"
          label="转舍数量 (只)"
          :value="obj.changeCricleCount"
          required
          is-link
          label-width="60%"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true, message: '请完善转舍数量' }]"
          @click="editEarLabel"
        />
        <van-button native-type="button" plain color="#37B5B5" @click="scanClick()" class="addbtn" type="primary"
          >扫一扫</van-button
        >
      </van-cell>
      <div class="spacing" />
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 85%; margin: auto; margin-top: 50px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Calendar,
  RadioGroup,
  Radio,
  Dialog,
  Toast,
  DatetimePicker,
  Picker,
  Button,
  Icon,
  Popup,
  Cell
} from 'vant'
import UploadImg from '@/components/uploadImg'
import TitlePanel from '@/components/titlePanel'
import dayjs from 'dayjs'
import { getValue, setValue, clearValue } from '@/utils/auth'
import { getHandle, postHandle } from '../../api'
export default {
  components: {
    UploadImg,
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component
  },
  data() {
    return {
      showPicker2: false,
      contentList: '',
      fileInfoList: [],
      currentDate: new Date(),
      showPicker1: false,
      loading: false,
      flag: true,
      //   typeList: [],
      //   resultList: [],
      isDisabled: false,
      natureShows: false,
      natureShows2: false,
      natureShows3: false,
      natureNameList: [],
      siteList: [],
      natureShow: false,
      natureNameLists: [],
      fertiliList: [],
      obj: {
        changeCircleDate: '',
        changeToHouseId: '',
        // changeToCricleId: "",
        changeCricleReasonCode: '',
        changeCricleCount: '',
        individualInfoIds: getValue('earTag2') ? JSON.parse(getValue('earTag2')) : []
      },
      contentObj: {},
      type: null,
      reasonS: [],
      reasonS_Code: [],
      houseS: [],
      houseS_ID: []
      // circleS: [],
      // circleS_ID: []
    }
  },
  created() {
    this.$bridge.register('backScanData', data => {
      if (JSON.parse(data).individualId) {
        let arr = [JSON.parse(data).individualId]
        setValue('earTag2', JSON.stringify(arr))
        this.obj.changeCricleCount = 1
        this.obj.individualInfoIds = arr
      } else {
        Toast('羊只信息未录入')
      }
    })
    this.$bridge.register('refresh', data => {
      // 请求转圈原因/羊舍列表数据
      this.getUnitList()
      this.getHouseList()
      // 请求详情数据
      this.getEditData()
    })
  },
  mounted() {},
  methods: {
    scanClick() {
      this.$bridge.call('base.scanOneScan')
    },

    editEarLabel() {
      // 保存编辑耳标页面需要的数据
      // 跳转编辑耳标页面
      setValue('earTag2', JSON.stringify(this.obj.individualInfoIds))
      setValue('addChangeCircle-obj', JSON.stringify({ ...this.obj }))
      this.$bridge.call('addCheckEarTag2')
    },
    // 请求详情数据
    getEditData() {
      getHandle(`/agri/api/yzbzh/changeCircleRecord/queryDetail/${getValue('changeCircle-view-id')}`).then(res => {
        this.obj.changeCircleDate = getValue('addChangeCircle-obj')
          ? this.addHuiXian('changeCircleDate')
          : res.data.changeCircleDate
        this.obj.changeToHouseId = getValue('addChangeCircle-obj')
          ? this.addHuiXian('changeToHouseId')
          : res.data.changeToHouseName
        // this.obj.changeToCricleId = getValue('addChangeCircle-obj') ? this.addHuiXian('changeToCricleId') :res.data.changeToCricleName
        this.obj.changeCricleReasonCode = getValue('addChangeCircle-obj')
          ? this.addHuiXian('changeCricleReasonCode')
          : res.data.changeCricleReason.name
        this.obj.changeCricleCount = getValue('earTag2')
          ? JSON.parse(getValue('earTag2')).length
          : res.data.changeCricleCount
        this.obj.individualInfoIds = getValue('earTag2') ? JSON.parse(getValue('earTag2')) : res.data.individualInfoIds
        // 拿到详情数据之后,需要根据舍请求圈
        this.getCircleList({
          houseId: this.houseS_ID[this.houseS.indexOf(this.obj.changeToHouseId)]
        })
      })
    },
    // 选择耳标之后,回显已经填写过的数据项
    addHuiXian(param) {
      return getValue('addChangeCircle-obj') ? JSON.parse(getValue('addChangeCircle-obj'))[param] : ''
    },
    // 请求单位列表
    getUnitList() {
      getHandle('/agri/api/common/businessData/queryList', { pCode: 'T000010_CHANGE_CIRCLE_REASON_TYPE' }).then(res => {
        console.log(res)
        res.data.rows.forEach(item => {
          this.reasonS.push(item.name)
          this.reasonS_Code.push(item.code)
        })
      })
    },
    // 请求舍信息列表
    getHouseList() {
      getHandle('/agri/api/yzbzh/HouseInfo/queryList').then(res => {
        console.log(res)
        this.houseS = []
        this.houseS_ID = []
        res.data.rows.forEach(item => {
          this.houseS.push(item.houseName)
          this.houseS_ID.push(item.id)
        })
      })
    },

    //时间
    onConfirmStartDate(value) {
      this.obj.changeCircleDate = dayjs(value).format('YYYY-MM-DD')
      this.showPicker1 = false
    },
    //疫苗接种数量这里是多选写的时候改下逻辑
    onConfirmTypes(value) {
      let index = this.fertiliList.indexOf(value)
      if (index == -1) {
        this.fertiliList.push(value)
      } else {
        this.fertiliList.splice(index, 1)
      }
      this.obj.FertilizersPesticides = this.fertiliList.map(item => item.label).join(',')
      this.natureShow = false
    },
    //选择舍
    onConfirmType(value) {
      this.obj.changeToHouseId = value
      this.natureShows = false
      // 选择完舍,根据舍id选择圈
      let params = {
        houseId: this.houseS_ID[this.houseS.indexOf(value)]
      }
      this.getCircleList(params)
    },
    // // 选择圈
    // onConfirmType2(value) {
    //   this.obj.changeToCricleId = value
    //   this.natureShows2 = false
    // },
    // 选择原因
    onConfirmType3(value) {
      this.obj.changeCricleReasonCode = value
      this.natureShows3 = false
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.loading = true
      // let imgInfos = this.obj.imgInfos.map((item) => item.url).join(",");
      // 发送保存网络请求
      this.onSave()
    },
    onSave() {
      const params = {
        changeCircleDate: this.obj.changeCircleDate,
        changeCricleReasonCode: this.reasonS_Code[this.reasonS.indexOf(this.obj.changeCricleReasonCode)],
        changeCricleCount: this.obj.changeCricleCount,
        individualInfoIds: getValue('earTag2') ? JSON.parse(getValue('earTag2')) : [],
        changeToHouseId: this.houseS_ID[this.houseS.indexOf(this.obj.changeToHouseId)],
        // changeToCricleId: this.circleS_ID[this.circleS.indexOf(this.obj.changeToCricleId)],
        houseInfoId: getValue('fzmHourseId') || '089ba3bc-be8f-4d5e-99da-f5489c8503f1',
        subjectInfoId: getValue('subjectInfoId'),
        tenantCode: getValue('tenantCode'),
        callChannel: getValue('callChannel'),
        loginUserId: getValue('loginUserId')
      }
      postHandle(`/agri/api/yzbzh/changeCircleRecord/update/${getValue('changeCircle-view-id')}`, params).then(res => {
        console.log(res)
        // 新增成功跳转列表页
        if (res.status == 0) {
          Toast.success('操作成功')
          clearValue('earTag2')
          this.$bridge.call('base.closePage')
        } else {
          Toast.fail(res.msg || '操作失败')
          this.loading = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tip {
  padding-top: 15px;
  color: #999999;
  font-size: 12px;
  line-height: 16px;
  margin: auto;
}
.btn {
  width: 80%;
  margin: 50px auto 0 auto;
}
.btn > div {
  height: 50px;
  background: #2871fe;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  color: #ffffff;
  font-size: 17px;
}
.btn .cancel {
  margin-top: 20px;
  background: rgba(40, 113, 254, 0.1);
  border: 1px solid #2871fe;
  color: #2871fe;
}
::v-deep .van-field__label {
  width: 6em;
}
.bthStyle {
  width: 56px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #2871fe;
}
.active {
  background-color: #fff;
  color: #2871fe;
}
.add-btn {
  padding-bottom: 20px;
}
.addbtn {
  width: 50px;
  height: 24px;
  font-size: 13px;
  padding: 0;
  margin-right: 13px;
  z-index: 10;
  float: right;
  margin-top: -38px;
}
.btnfrom {
  padding: 1px 0;
}
.fromInput {
  width: 86%;
}
</style>
